package com.ruoyi.web.controller.blog;

import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.blog.domain.TBlogContent;
import com.ruoyi.blog.domain.TCategory;
import com.ruoyi.blog.dto.TAddBlog;
import com.ruoyi.blog.service.ITBlogConfigService;
import com.ruoyi.blog.service.ITBlogContentService;
import com.ruoyi.blog.service.ITCategoryService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sql.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.blog.domain.TBlog;
import com.ruoyi.blog.service.ITBlogService;

/**
 * 博客Controller
 * 
 * @author yang
 * @date 2021-11-15
 */
@RestController
@RequestMapping("/blog/blog")
public class TBlogController extends BaseController
{
    @Autowired
    private ITBlogService tBlogService;

    @Autowired
    private ITBlogContentService tBlogContentService;

    @Autowired
    private ITCategoryService tCategoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ITBlogConfigService tBlogConfigService;

    /**
     * 查询博客列表
     */
    @PreAuthorize("@ss.hasPermi('blog:blog:list')")
    @GetMapping("/list")
    public TableDataInfo list(TBlog tBlog)
    {
        startPage();
        List<TBlog> list = tBlogService.selectTBlogList(tBlog);
        return getDataTable(list);
    }

    /**
     * 导出博客列表
     */
    @PreAuthorize("@ss.hasPermi('blog:blog:export')")
    @Log(title = "博客", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TBlog tBlog) throws IOException
    {
        List<TBlog> list = tBlogService.selectTBlogList(tBlog);
        ExcelUtil<TBlog> util = new ExcelUtil<TBlog>(TBlog.class);
        util.exportExcel(response, list, "博客数据");
    }

    /**
     * 获取博客详细信息
     */
    @PreAuthorize("@ss.hasPermi('blog:blog:query')")
    @GetMapping(value = "/{blogId}")
    public AjaxResult getInfo(@PathVariable("blogId") Long blogId)
    {
        return AjaxResult.success(tBlogService.selectTBlogByBlogId(blogId));
    }

    /**
     * 新增博客
     */
    @PreAuthorize("@ss.hasPermi('blog:blog:add')")
    @Log(title = "博客", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAddBlog tBlog)
    {
        TBlogContent tBlogContent = new TBlogContent();
        tBlogContent.setContent(tBlog.getContent());
        tBlogContent.setContentWrite(tBlog.getContentWrite());
        int res = tBlogContentService.insertTBlogContent(tBlogContent);
        TBlog blog = new TBlog();
        if(res == 1) {
            blog.setTitle(tBlog.getTitle());
            blog.setAuthorId(SecurityUtils.getUserId());
            blog.setCategoryId(tBlog.getCategoryId());
            blog.setContentId(tBlogContent.getContentId());
            blog.setCoverImgUrl(tBlog.getCoverImgUrl());
            blog.setIntroduction(tBlog.getIntroduction());
            blog.setStatus(tBlog.getStatus());
            blog.setIsHot(tBlog.getIsHot()?"1":"0");
            blog.setDelFlag("0");
            blog.setLikeCount(0L);
            blog.setCreateBy(tBlog.getCreateBy());
            return toAjax(tBlogService.insertTBlog(blog));
        }else{
            return AjaxResult.error("新增失败，请联系系统管理员！");
        }

    }

    /**
     * 修改博客
     */
    @PreAuthorize("@ss.hasPermi('blog:blog:edit')")
    @Log(title = "博客", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAddBlog tBlog)
    {
        TBlogContent tBlogContent = new TBlogContent();
        tBlogContent.setContentId(tBlogService.selectTBlogByBlogId(tBlog.getBlogId()).getContentId());
        tBlogContent.setContent(tBlog.getContent());
        tBlogContent.setContentWrite(tBlog.getContentWrite());
        int res = tBlogContentService.updateTBlogContent(tBlogContent);
        TBlog blog = new TBlog();
        if(res == 1) {
            blog.setBlogId(tBlog.getBlogId());
            blog.setTitle(tBlog.getTitle());
            blog.setCategoryId(tBlog.getCategoryId());
            blog.setContentId(tBlogContent.getContentId());
            blog.setCoverImgUrl(tBlog.getCoverImgUrl());
            blog.setIntroduction(tBlog.getIntroduction());
            blog.setStatus(tBlog.getStatus());
            blog.setIsHot(tBlog.getIsHot()?"1":"0");
            blog.setDelFlag("0");
            blog.setLikeCount(0L);
            blog.setCreateBy(tBlog.getCreateBy());
            return toAjax(tBlogService.updateTBlog(blog));
        }else{
            return AjaxResult.error("新增失败，请联系系统管理员！");
        }
    }

    /**
     * 删除博客
     */
    @PreAuthorize("@ss.hasPermi('blog:blog:remove')")
    @Log(title = "博客", businessType = BusinessType.DELETE)
	@DeleteMapping("/{blogIds}")
    public AjaxResult remove(@PathVariable Long[] blogIds)
    {
        return toAjax(tBlogService.deleteTBlogByBlogIds(blogIds));
    }

    /**
     * 通过前端查询博客列表
     */
    @GetMapping("/fromIndex/blogList")
    public AjaxResult listBlogFromIndex(TBlog tBlog,String orderBy,Boolean categoryFlag)
    {
        Map<String,Object> res = new HashMap<>();
        //查询最新内容
        startPage();
        List<TBlog> list = tBlogService.selectListBlogFromIndex(tBlog,orderBy);
        res.put("blogList",list);
        res.put("total",new PageInfo(list).getTotal());
        //查询类型
        if(categoryFlag != null && categoryFlag) {
            TCategory queryCate = new TCategory();
            queryCate.setStatus("0");
            queryCate.setDelFlag("0");
            res.put("categoryList", tCategoryService.selectTCategoryList(queryCate));
        }
        return new AjaxResult(200,"查询成功",res);
    }

    /**
     * 通过前端查询博客列表
     */
    @GetMapping("/fromIndex/index")
    public AjaxResult listFromIndex(TBlog tBlog,String orderBy)
    {
        Map<String,Object> res = new HashMap<>();
        //查询最新内容
        startPage();
        List<TBlog> list = tBlogService.selectListBlogFromIndex(tBlog,"update_time desc");
        res.put("newBlog",list);
        //查询博客排行
        startPage();
        list = tBlogService.selectListBlogFromIndex(tBlog,"like_count desc");
        res.put("hotBlog",list);
        //查询类型
        List<TCategory> listCategory;
        listCategory = redisCache.getCacheList("blogCategory");
        System.out.println(listCategory.size());
        if(listCategory == null){
            TCategory queryCate = new TCategory();
            queryCate.setStatus("0");
            queryCate.setDelFlag("0");
            listCategory = tCategoryService.selectTCategoryList(queryCate);
            redisCache.setCacheList("blogCategory",listCategory);
            redisCache.expire("blogCategory",900);
        }
        res.put("categoryList",listCategory);
        return new AjaxResult(200,"查询成功",res);
    }


    /**
     * 通过前端查询博客列表
     */
    @GetMapping("/fromIndex/oneBlog")
    @Transactional
    public AjaxResult oneBlogFromIndex(TBlog tBlog,String orderBy)
    {
        orderBy = SqlUtil.escapeOrderBySql(orderBy);
        Map<String,Object> res = new HashMap<>();
        //查询最新内容
        tBlog.setStatus("0");
        tBlog.setDelFlag("0");
        List<TBlog> listBlog = tBlogService.selectListBlogFromIndex(tBlog,orderBy);
        if(listBlog.size() == 0){
            return AjaxResult.error("查询失败，请联系系统管理员！");
        }else{
            TBlog resBlog = listBlog.get(0);
            res.put("blog",resBlog);
            tBlogService.addLikeCount(resBlog.getBlogId(),resBlog.getLikeCount() + 1);
            tBlogConfigService.addTraffic();
            res.put("content",tBlogContentService.selectTBlogContentByContentId(resBlog.getContentId()));
        }
        return new AjaxResult(200,"查询成功",res);
    }



}
